
import MaterialSymbolsNotificationsActiveOutline from '~icons/material-symbols/notifications-active-outline'
import type { WebSocketMessage } from '@/type/all-type'
import router from '@/router'

/**
 * websocke处理类
 */
class WebSocketHandler {

    messageHandler: MessageTypeHandler

    static instance: WebSocketHandler

    constructor(private webSocket: WebSocket) {
        this.messageHandler = new MessageTypeHandler(webSocket);
        WebSocketHandler.instance = this
    }

    /**
     * 绑定webSocket事件处理函数
     */
    bind() {
        this.webSocket.addEventListener('open', this.open)
        this.webSocket.addEventListener('message', this.message)
        this.webSocket.addEventListener('close', this.close)
        this.webSocket.addEventListener('error', this.error)
    }


    private open(event: Event) {
        console.log("websocke连接成功", event)
        ElNotification({
            title: '提示',
            message: userInfoState().user.userName + WebSocketHandler.instance.greeting(),
            duration: 3000,
            icon: MaterialSymbolsNotificationsActiveOutline
        })
    }

    private message(messageEvent: MessageEvent) {
        //接收服务器发送过来的消息
        const data = messageEvent.data
        //将json字符串转成对象
        WebSocketHandler.instance.messageHandler.hander(JSON.parse(data))
    }


    private close(closeEvent: CloseEvent) {
        console.log("websocket连接已断开", closeEvent)
    }

    private error(errorEvent: Event) {
        console.log("websocket连接发生错误", errorEvent)
    }

    greeting(): string {
        // 获取当前时间
        const timeNow = new Date();
        // 获取当前小时
        const hours = timeNow.getHours();
        // 设置默认文字
        let text = ``;
        // 判断当前时间段
        if (hours >= 0 && hours <= 10) {
            text = ` 早上好! `;
        } else if (hours > 10 && hours <= 14) {
            text = ` 中午好! `;
        } else if (hours > 14 && hours <= 18) {
            text = ` 下午好! `;
        } else if (hours > 18 && hours <= 24) {
            text = ` 晚上好! `;
        }
        // 返回当前时间段对应的状态
        return text;
    }


}


class MessageTypeHandler {

    constructor(private webSocket: WebSocket) {

    }

    hander(message: WebSocketMessage) {
        switch (message.type) {
            case 'kick_off_line':
                this.kickOff()
                break
            case "workflow_assignee_task_notify":
                break
        }
    }

    /**
     * 将用户踢下线
     */
    private kickOff() {
        ElNotification({
            title: '提示',
            message: "您以在其他地方登陆5秒后自动跳转到登陆页面,若不是本人操作，建议重新登陆且修改密码。",
            type: 'warning',
            duration: 4500
        })
        //删除用户
        userInfoState().removeUser()
        //断开websocket连接
        this.webSocket.close(1000, '用户被踢出登陆主动断开连接')
        //跳转到登陆页面
        setTimeout(() => {
            router.push("/login")
        }, 4500)
    }

}


export { WebSocketHandler } 